/**
 * User: tengmt
 * Date: 14-12-17
 */
define(["app",
        "resources/ContactsResource",
        "services/TipsService",
        'directives/ImageCrop',
        "directives/common/OrgUserPicker"],
    function(app) {
        var deps = ["$scope","ContactsResource","$state","$stateParams","TipsService"];

        function controller($scope,ContactsResource,$state,$stateParams,TipsService) {
        	
        	var imageData;
        	
        	$scope.isSelectAll = false;
        	$scope.group = {}; //记录群组对象
        	$scope.selectedUserIdList = []; // //记录已勾选的成员 记录群组成员Id
        	$scope.relateGroups = [];
        	$scope.totalUsers = 0; //成员总数
        	
        	var url = $state.current.name;
        	if(url == "home.address.groupAdd"){ //新增
                $scope.group.createUserId = $scope.user.userId;
                $scope.group.createUserName = $scope.user.userName;
            }else{ //修改 通过groupId获取群组信息
            	queryData();
            }
        	
        	/**
             * 加载数据
             */
            function queryData(){
            	//通过groupId获取群组信息
            	ContactsResource.queryGroupById($stateParams.groupId).success(function(group){
            		if (group) {
            			if(group.picId){
            				$scope.groupPic = 'restful/userimage/getImage/' + group.picId;
            			}
            			$scope.totalUsers = group.contractUser.length || 0;
            			$scope.group = angular.copy(group);
                    	// 动态添加数据 渲染表格
            			$scope.relateGroups = angular.copy($scope.group.contractUser);
            		}
            	});
            }
        	
        	/**
        	 * 添加成员
        	 */
        	$scope.addUsers = function($chosenList){
        		$scope.totalUsers += $chosenList.length;
        		if($chosenList && $chosenList.length > 0){
        			for(var i = 0; i<$chosenList.length;i++){
        				var relateGroups = $scope.relateGroups;
        				var len = relateGroups.length;
        				var user = $chosenList[i];
        				var flag = true;
        				for(var j = 0; j<len;j++){
        					if(relateGroups[j].userId == $chosenList[i].userId){
        						flag = false;
        						break;
        					}
        				}
        				if(flag){
        					$scope.relateGroups[len] = {userId: user.userId, userName: user.userName, orgName: user.userOrgInfo};
        				}
        			}
        		}
        	};
        	
        	/**
        	 * 保存/修改
        	 */
        	$scope.saveGroup = function(){
        		if(!$scope.group.groupName) {
        			TipsService.show('请输入名称!');
        			return false;
        		}
//        		if (!imageData) {
//                    TipsService.show('请上传资讯号头像!');
//                    return false;
//                }
//        		if($scope.relateGroups.length == 0) {
//        			TipsService.show('请添加成员!');
//        			return false;
//        		}
        		if (imageData && imageData.file) {
                    uploadImage().success(function(result) {
                        $scope.group.picId = result.fileId;
                        saveOrUpdate();
                    });
                } else {
                	saveOrUpdate();
                }
        		// 发个通知
        		$scope.$bus.publish({
                    channel: 'newGroup',
                    topic: 'newGroup',
                    data: true
                });
            };
            
            $scope.goBack = function(){ 
            	$scope.$parent.selectGroup($scope.$parent.selectedGroupId);
            };
            
            /**
             * 保存
             */
            function saveOrUpdate() {
            	$scope.group.groupUsers = [];
            	$scope.group.managerList = [];
        		for(var i=0; i<$scope.relateGroups.length; i++) { //保存表格中的成员
        			$scope.group.groupUsers.push($scope.relateGroups[i].userId);
        			// 拷贝管理员信息
        			if($scope.relateGroups[i].manager){
        				$scope.group.managerList.push($scope.relateGroups[i].userId);
        			}
        		}
        		$scope.group.type = 0;
        		$scope.group.status = 0;
        		if($scope.group) {
        			ContactsResource.saveOrUpdateGroup($scope.group).success(function(groupsContacts){
            			if (groupsContacts) {
            				TipsService.show("<span class='glyphicon glyphicon-ok'></span>&nbsp;操作成功");
                            $scope.cancel();
            			}
                    });
        		}
            }
            
            /**
             * 删除
             */
            $scope.deleteUsers = function(){
                var userIds = getSelectedUserIdList();
                $scope.totalUsers = $scope.totalUsers - userIds.length; 
                if(userIds && userIds.length>0){
                	for(var i=0; i< userIds.length; i++){
                		for(var j=0; j< $scope.relateGroups.length; j++){
                			if(userIds[i] == $scope.relateGroups[j].userId){
                				user = $scope.relateGroups[j];
                				$scope.relateGroups.splice(j,1);
                				break;
                			}
                		}
                	}
                }else{
                    TipsService.show("<span class='glyphicon glyphicon-ok'></span>&nbsp;请至少选择一名成员");
                }
            };
            
            
            /**
             * 获取所有已选的用户ID
             */
            function getSelectedUserIdList(){
                var selectedList = [];
                if(!$scope.relateGroups){
                    return;
                }

                for(var i = 0;i<$scope.relateGroups.length;i++){
                    var userId = $scope.relateGroups[i].userId;
                    if($scope.selectedUserIdList[userId]){
                        selectedList.push(userId);
                    }
                }
                return selectedList;
            }
            
            /**
             * 选择全部用户
             */
            $scope.toggleSelectAll = function(){
                if($scope.isSelectAll){
                    $scope.selectedUserIdList = {};
                    $scope.isSelectAll = false;
                }else{
                    for(var i = 0; i<$scope.relateGroups.length;i++){
                        $scope.selectedUserIdList[$scope.relateGroups[i].userId] = 'selected';
                        $scope.isSelectAll = true;
                    }
                }
            };

            /**
             * 当前选择的用户
             * @param userId
             */
            $scope.toggleUser = function(userId){
                if($scope.selectedUserIdList[userId]){
                    delete  $scope.selectedUserIdList[userId];
                } else{
                    $scope.selectedUserIdList[userId] = 'selected';
                }
            };
            
            //跳转到群组列表页
            $scope.cancel = function(){
            	$scope.isSelectAll = false;
            	$scope.group = {}; //记录群组对象
            	$scope.selectedUserIdList = []; // //记录已勾选的成员 记录群组成员Id
            	$scope.relateGroups = [];
            	$scope.totalUsers = 0; //成员总数
            };
            
            /**
             * 图片数据
             */
            $scope.$bus.subscribe({
                channel: 'image',
                topic: 'crop',
                callback: function(data) {
                    imageData = data;
                }
            });
            
            /**
             * 图片剪裁
             */
            function uploadImage() {
                var formData = new FormData();
                formData.append("file", imageData.file);

                var cropParam = {
                    cropX: imageData.cropX || 0,
                    cropY: imageData.cropY || 0,
                    cropW: imageData.cropW || 0,
                    cropH: imageData.cropH || 0
                };
                return ContactsResource.uploadCropImage(formData, cropParam);
            }
        }

        controller.$inject = deps;
        app.lazy.controller("GroupEditController", controller);
    });
